package com.dfwl.packageio.moudle;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.ViewGroup;

import com.dfwl.packageio.R;
import com.dfwl.packageio.core.base.BaseActivity;
import com.google.zxing.Result;

import me.dm7.barcodescanner.zxing.ZXingScannerView;

/**
 * @auth &{zhujiule}
 * @date 2018/8/13
 * @copyright 杭州物恋网科技有限公司
 **/
public class ScanActivity extends BaseActivity implements ZXingScannerView.ResultHandler {
   private ZXingScannerView mScannerView;

   @Override
   public void onCreate(Bundle state) {
      super.onCreate(state);
      setContentView(R.layout.activity_scan);

      ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
      mScannerView = new ZXingScannerView(this);
      contentFrame.addView(mScannerView);
   }

   @Override
   public void onResume() {
      super.onResume();
      mScannerView.setResultHandler(this);
      mScannerView.startCamera();
   }

   @Override
   public void onPause() {
      super.onPause();
      mScannerView.stopCamera();
   }

   @Override
   public void handleResult(Result rawResult) {
//      Toast.makeText(this, "Contents = " + rawResult.getText() +
//            ", Format = " + rawResult.getBarcodeFormat().toString(), Toast.LENGTH_SHORT).show();
      String mText = rawResult.getText();
      Intent mIntent = new Intent();
      mIntent.putExtra("content",mText);
      setResult(Activity.RESULT_OK,mIntent);
      finish();
      // Note:
      // * Wait 2 seconds to resume the preview.
      // * On older devices continuously stopping and resuming camera preview can result in freezing the app.
      // * I don't know why this is the case but I don't have the time to figure out.
      Handler handler = new Handler();
      handler.postDelayed(new Runnable() {
         @Override
         public void run() {
            mScannerView.resumeCameraPreview(ScanActivity.this);
         }
      }, 2000);
   }
}